const TYPE_DISPLAY = {
  single: '单选题',
  multiple: '多选题',
  judge: '判断题'
};

Component({
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },

  properties: {
    question: {
      type: Object,
      value: {}
    },
    value: {
      type: null,
      value: null
    },
    index: {
      type: Number,
      value: 1
    },
    total: {
      type: Number,
      value: 1
    },
    disabled: {
      type: Boolean,
      value: false
    },
    reveal: {
      type: Boolean,
      value: false
    },
    analysis: {
      type: String,
      value: ''
    },
    remainingTime: {
      type: String,
      value: ''
    }
  },

  data: {
    formattedOptions: [],
    displayType: ''
  },

  lifetimes: {
    attached() {
      this.prepareQuestion();
    }
  },

  observers: {
    question() {
      this.prepareQuestion();
    },
    value() {
      this.prepareOptions();
    },
    reveal() {
      this.prepareOptions();
    }
  },

  methods: {
    prepareQuestion() {
      const displayType = this.properties.question.displayType
        ? this.properties.question.displayType
        : TYPE_DISPLAY[this.properties.question.type] || '';
      this.setData({ displayType });
      this.prepareOptions();
    },

    prepareOptions() {
      const question = this.properties.question || {};
      const rawOptions = Array.isArray(question.options) ? question.options : [];
      const correctAnswers = this.extractCorrectAnswers(question);

      const selected = this.normalizeValue(this.properties.value, question.type);
      const formatted = rawOptions.map((option, idx) => {
        const normalized = this.normalizeOption(option, idx);
        const isChecked = selected.includes(normalized.value);
        const label = String.fromCharCode(65 + idx);
        let state = '';
        if (this.properties.reveal) {
          if (correctAnswers.includes(normalized.value)) {
            state = 'correct';
          } else if (isChecked) {
            state = 'incorrect';
          }
        }
        return Object.assign({}, normalized, {
          label,
          checked: isChecked,
          state
        });
      });

      this.setData({ formattedOptions: formatted });
    },

    normalizeOption(option, idx) {
      if (typeof option === 'string') {
        const value = option;
        return {
          value: String(value),
          text: option,
          description: ''
        };
      }

      const value =
        option.value !== undefined
          ? option.value
          : option.id !== undefined
          ? option.id
          : idx;
      const text = option.text || option.label || option.title || option.content || String(value);
      const description = option.description || option.desc || '';

      return {
        value: String(value),
        text,
        description
      };
    },

    normalizeValue(value, type) {
      if (type === 'multiple') {
        if (Array.isArray(value)) {
          return value.map((item) => String(item));
        }
        if (typeof value === 'string') {
          return value
            .split(',')
            .map((item) => item.trim())
            .filter(Boolean);
        }
        return [];
      }
      if (value === null || value === undefined) {
        return [];
      }
      return [String(value)];
    },

    extractCorrectAnswers(question) {
      if (!this.properties.reveal) {
        return [];
      }
      const answers = [];
      if (Array.isArray(question.correctAnswers)) {
        question.correctAnswers.forEach((item) => answers.push(String(item)));
      } else if (Array.isArray(question.answers)) {
        question.answers.forEach((item) => answers.push(String(item)));
      } else if (Array.isArray(question.correctOptions)) {
        question.correctOptions.forEach((item) => answers.push(String(item)));
      } else if (question.answer !== undefined && question.answer !== null) {
        answers.push(String(question.answer));
      }
      return answers;
    },

    onOptionToggle(event) {
      if (this.properties.disabled) {
        return;
      }
      const value = event.detail?.value ?? event.currentTarget?.dataset?.value;
      const question = this.properties.question || {};
      const type = question.type || 'single';

      if (type === 'multiple') {
        const current = new Set(this.normalizeValue(this.properties.value, type));
        if (current.has(String(value))) {
          current.delete(String(value));
        } else {
          current.add(String(value));
        }
        this.triggerEvent('change', {
          value: Array.from(current),
          questionId: question.id
        });
      } else {
        this.triggerEvent('change', {
          value: value,
          questionId: question.id
        });
      }
    }
  }
});
